const https = require('https');
var qs = require('querystring');
require('chromedriver');
const { Builder, By, Key, until } = require('selenium-webdriver');
const { resolve } = require('path');
const { rejects } = require('assert');
var driver = new Builder().forBrowser('chrome').build();
var cookieList = [];

//账号列表
var userLogin = ["1418154909", "2893303772", "3502258644"];
//打开浏览器
(function open() {
  driver.get("https://mail.qq.com/").then(() => {
    console.log("页面加载完成");
    iframe = driver.findElement(By.id("login_frame"));
    driver.switchTo().frame(iframe).then(() => {
      login();
    });
  });
})()
//登录
function login() {
  let cookie = ""
    (async function isPageload() {
      console.log("正在登录中...")
      await driver.findElement(By.id("qlogin_list")).findElement(By.xpath("//a[@uin=" + userLogin[0] + "]")).click();
      let as = await driver.wait(until.elementLocated(By.id('useraddr'))).catch(() => {
        console.log("登录超时");
      });
      if (!as) return;
      await getCookie().then(res => {
        res.forEach((item, index) => {
          if (index == res.length - 1) {
            cookie += (item.name + "=" + item.value);
          } else {
            cookie += (item.name + "=" + item.value + "; ")
          }
        })
      });
      

    function create(){
        ajax({
          "cb2dee24e50d987120dc1836d0418bef": "46291a7b17ebf25714f4848ebcd0d095",
          "sid": "kEzRpepaF2ORlTln",
          "from_s": "cnew",
          "signtype": 0,
          "to": "%22范剑涛%22<1418154909@qq.com>",
          "subject": "这是程序发的",
          "content__html": "<div>这是程序发的</div>",
          "sendmailname": "2893303772@qq.com",
          "savesendbox": 1,
          "actiontype": "send",
          "sendname": "这些年",
          "acctid": 0,
          "separatedcopy": false,
          "s": "comm",
          "hitaddrbook": 0,
          "selfdefinestation": -1,
          "domaincheck": 0,
          "cgitm": 1592967209478,
          "clitm": 1592967209286,
          "comtm": 1592967326230,
          "logattcnt": 0,
          "logattsize": 0,
          "timezone": 28800,
          "timezone_dst": 0,
          "cginame": "compose_send",
          "ef": "js",
          "t": "compose_send.json",
          "resp_charset": "UTF8"
        }, cookie).then(res=>{
           driver.sleep(2000).then(()=>{
            console.log("创建成功")
            create({
              "cb2dee24e50d987120dc1836d0418bef": "46291a7b17ebf25714f4848ebcd0d095",
              "sid": "kEzRpepaF2ORlTln",
              "from_s": "cnew",
              "signtype": 0,
              "to": "%22范剑涛%22<1418154909@qq.com>",
              "subject": "这是程序发的",
              "content__html": "<div>这是程序发的</div>",
              "sendmailname": "2893303772@qq.com",
              "savesendbox": 1,
              "actiontype": "send",
              "sendname": "这些年",
              "acctid": 0,
              "separatedcopy": false,
              "s": "comm",
              "hitaddrbook": 0,
              "selfdefinestation": -1,
              "domaincheck": 0,
              "cgitm": 1592967209478,
              "clitm": 1592967209286,
              "comtm": 1592967326230,
              "logattcnt": 0,
              "logattsize": 0,
              "timezone": 28800,
              "timezone_dst": 0,
              "cginame": "compose_send",
              "ef": "js",
              "t": "compose_send.json",
              "resp_charset": "UTF8"
             },cookie)
           })
        }).catch(err=>{

        });

      }
     await create();
    
    })();

  function ajax(data, cookie) {
    return new Promise((resolve, reject) => {
      var post_data = { ...data };//这是需要提交的数据  
      var content = qs.stringify(post_data);
      var options = {
        hostname: 'mail.qq.com',
        port: 443,
        path: '/cgi-bin/do?sid=kEzRpepaF2ORlTln&action=checkpoint&url=https%3A%2F%2Fmail.qq.com%2Fcgi-bin%2Fmail_list%3Fsid%3DkEzRpepaF2ORlTln%26folderid%3D4%26page%3D0%26loc%3Dfolderlist%2C%2C%2C4%23stattime%3D1592964075944&sid=kEzRpepaF2ORlTln',
        method: 'POST',
        headers: {
          "Content-Type": 'application/x-www-form-urlencoded; charset=UTF-8',
          "cookie": cookie,
          "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
        }
      };
      var req = https.request(options, function (res) {
        console.log('STATUS(响应状态): ' + res.statusCode);
        console.log('HEADERS(响应头): ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
          console.log('BODY(响应体): ' + chunk);
          resolve(chunk);
        });
      });

      req.on('error', function (e) {
        console.log('problem with request(请求失败): ' + e.message);
        reject(e);
      });
      // 将数据写入请求体
      req.write(content);//注意这个地方  
      req.end();
    })

  }
  // driver.findElement(By.id("qlogin_list")).findElements(By.className("face")).then((el) => {
  //   el[2].click();
  // });
  // driver.sleep(2000).then(() => {
  //   driver.findElement(By.id('folder_1')).click();
  //   driver.sleep(2000).then(() => {
  //     // console.log(driver.getSession(),"Session")
  //     driver.manage().getCookies().then((res) => {
  //       // console.log(res, "cookies")
  //         cookieList=res;
  //         // loginOut();

  //     }); 
  //   })
  // })
}
function getCookie() {
  console.log('正在获取cookies');
  return driver.manage().getCookies();
}
//退出登录
function loginOut() {
  driver.findElements(By.className('toptitle')).then(arr => {
    arr[3].click();
    // console.log("准备推出")
    driver.sleep(60 * 1000 * 10).then(() => {
      open();
    })
  });
}
// driver.sleep(5000);
// iframe = driver.findElement(By.id("login_frame"))
// driver.switchTo().frame(iframe).then(()=>{
//   driver.findElement(By.id("qlogin_list")).findElement(By.id('q_low_login_wording')).click();
// });
// console.log(driver.findElement(By.id("qlogin_list")));
// console.log(driver.findElement(By.id("qlogin_list")))
// js = "document.querySelector('#login_frame').contentWindow.document.querySelector('#img_1418154909').click()"
// driver.executeScript(js);
// switch_to_default_content()

// this.$axios
//         .post("/api/index/login/send_sms_code", {
//           phone: this.phone,
//           captcha_code: this.captcha_code
//         },{withCredentials:true})
//         .then(res => {
//           console.log(666, res);
//           if (res.data.code != 200) {
//             const { msg } = res.data;
//             Toast(msg);
//           }
//         })
//         .catch(err => {
//           console.log(666, err);
//           Toast("内部错误");
//         });
//     },

